package com.web.portal.authentication;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.web.portal.entity.Admin;
import com.web.portal.service.AdminService;
@Service("webDetailsService")
public class WebDetailService implements UserDetailsService {
	@Autowired
	AdminService adminService;
	

	

	public AdminService getAdminService() {
		return adminService;
	}

	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		Admin admin= new Admin();
		List<Admin> adminList=adminService.getList(admin);
		
		if (adminList.isEmpty()) {
			throw new UsernameNotFoundException("Username not found");
		}
		
		 List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		authorities.add(new  SimpleGrantedAuthority("ROLE_ADMIN"));
		/*UsernamePasswordAuthenticationToken uat = new UsernamePasswordAuthenticationToken(adminList.get(0).getUserName(), adminList.get(0).getPassword(), authorities);
		uat.setDetails(adminList.get(0));
		SecurityContext context = SecurityContextHolder.getContext();
		Authentication userAuth = authenticationManager.authenticate(uat);

		context.setAuthentication(userAuth);*/
		return new User(adminList.get(0).getUserName(), adminList.get(0).getPassword(), authorities);

	}
}
